"use strict";

import Vue from "vue";
import axios from "axios";
import { Message, MessageBox } from "element-ui";

const { baseUrl } = require("~/config");

let config = {
  baseURL: baseUrl,
  timeout: 60 * 1000, // Timeout
  withCredentials: true, // Check cross-site Access-Control
};

const typewwwform = "application/x-www-form-urlencoded;charset=UTF-8", // 数据是url query格式
  typemultipart = "multipart/form-data;charset=UTF-8", // 要是数据是 FormData格式
  typejson = "application/json;charset=UTF-8"; // 数据是JSON格式

const showErrorMessage = function(message, options, type, cb) {
  message = message || "网络好像有点问题";
  if (type == "alert") {
    MessageBox.alert(
      message,
      Object.assign(
        {},
        {
          confirmButtonText: "确定",
          type: "error",
          closeOnClickModal: false,
          closeOnPressEscape: false,
          showClose: false,
          callback: (action) => {
            cb && cb();
          },
        },
        options || {}
      )
    );
  } else {
    Message(
      Object.assign(
        {},
        {
          showClose: false,
          message: message,
          type: "error",
        },
        options || {}
      )
    );
  }
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    if (config.method === "post") {
      config.headers["Content-Type"] = typejson;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    // 响应拦截
    const { data } = response;
    if (data) return data;

    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue, options) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      },
    },
    $axios: {
      get() {
        return _axios;
      },
    },
  });
};

Vue.use(Plugin);

export default Plugin;
